package site.wanjiahao.util;

import site.wanjiahao.message.Message;

import java.io.*;
import java.nio.charset.StandardCharsets;

public interface Serialize {

    <T> byte[] serialize(T t);

    <T> T deserialize(byte[] bytes, Class<T> clazz);

    enum SerializeAlgorithm implements Serialize {

        JDK {
            @Override
            public <T> byte[] serialize(T t) {
                try (
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        ObjectOutputStream oos = new ObjectOutputStream(bos);
                ) {
                    oos.writeObject(t);
                    return bos.toByteArray();
                } catch (IOException ioException) {
                    throw new RuntimeException(ioException);
                }
            }

            @Override
            public <T> T deserialize(byte[] bytes, Class<T> clazz) {
                try (
                        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
                        ObjectInputStream ois = new ObjectInputStream(bis);
                ) {
                    return clazz.cast(ois.readObject());
                } catch (IOException | ClassNotFoundException ioException) {
                    throw new RuntimeException(ioException);
                }
            }
        },

        JSON {
            @Override
            public <T> byte[] serialize(T t) {
                return com.alibaba.fastjson.JSON.toJSONString(t).getBytes(StandardCharsets.UTF_8);
            }

            @Override
            public <T> T deserialize(byte[] bytes, Class<T> clazz) {
                return com.alibaba.fastjson.JSON.parseObject(new String(bytes), clazz);
            }
        }
    }

}
